const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
// 托管静态文件（前端页面）
app.use(express.static(__dirname));
const server = http.createServer(app);
const io = new Server(server, {
  cors: {
    origin: "*"
  }
});

let onlineUsers = [];
let messageHistory = []; // 存储最近10条消息

io.on('connection', (socket) => {
  socket.on('join', (username, callback) => {
    if (onlineUsers.includes(username)) {
      callback({ success: false, message: '用户名已存在，请更换' });
      return;
    }
    onlineUsers.push(username);
    socket.username = username;
    callback({ success: true });
    // 发送最近10条历史消息给新用户
    socket.emit('messageHistory', messageHistory);
    io.emit('userJoined', `${username} 加入了聊天室`);
  });

  socket.on('chatMessage', (message) => {
    // 存储消息到历史（保留最近10条）
    messageHistory.push({ username: socket.username, message });
    if (messageHistory.length > 10) {
      messageHistory.shift(); // 移除最早的消息
    }
    io.emit('message', { username: socket.username, message });
  });

  // 处理主动退出事件
  socket.on('logout', (username) => {
    if (onlineUsers.includes(username)) {
      onlineUsers = onlineUsers.filter(user => user !== username);
      io.emit('userLeft', `${username} 离开了聊天室`);
    }
  });

  socket.on('disconnect', () => {
    if (socket.username) {
      onlineUsers = onlineUsers.filter(user => user !== socket.username);
      io.emit('userLeft', `${socket.username} 离开了聊天室`);
    }
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});